/** @format */

import * as Router from 'koa-router';
import {config} from '../config';
import {sql} from '../mysql';
import {to, readFile} from '../utils';
import * as path from 'path';
import * as fs from 'fs';

interface IData {
  id: number;
  title: string;
  category: string;
  markdown: string;
  html: string;
  release_date: string;
  visits: number;
}

const {apiVersion} = config;

const urls = {
  getArticleList: '/getArticleList',
  getArticle: '/getArticle',
  getCategory: '/getCategory',
  getInterfaceConfig: '/getInterfaceConfig',
  postcomment: '/postcomment',
};

// 拼接 api 版本
Object.keys(urls).forEach((item: string) => {
  (urls as any)[item] = apiVersion + (urls as any)[item];
});

const router = new Router();

// 获取配置信息
router.use('/', async (ctx, next) => {
  const [errGetConfig, configData]: any = await to(readFile(path.resolve(`${__dirname}/../config/setting.json`)));

  if (errGetConfig) {
    ctx.body = {
      msgCode: 1,
      msg: '系统错误，请稍后重试',
    };
    return;
  }
  ctx.state.config = JSON.parse(configData);

  await next();
});

router.get(urls.getArticleList, async ctx => {
  const UIRowsPerPage = ctx.state.config.UIRowsPerPage;
  const page = ctx.query.page;
  const [errArticleList, articleListData]: any = await to(
    sql(`SELECT id,title,markdown FROM article ORDER BY id DESC LIMIT ${(page - 1) * UIRowsPerPage}, ${UIRowsPerPage}`),
  );

  if (errArticleList) {
    // 处理错误
    return;
  } else {
    articleListData.results.forEach((item: IData, index: number) => {
      const pos = item.markdown.indexOf('@@');
      articleListData.results[index].markdown = item.markdown.slice(0, pos);
    });
    ctx.body = articleListData.results;
  }

  const [errArticleListLen, articleListLenData]: any = await to(sql(`SELECT COUNT(id) FROM article`));
  if (errArticleListLen) {
    // 处理错误
    return;
  } else {
    const isNextPage = articleListLenData.results[0]['COUNT(id)'] > page * UIRowsPerPage;
    const resData = {
      data: {
        articleList: articleListData.results,
        isNextPage,
      },
    };
    ctx.body = resData;
  }
});

router.get(urls.getArticle, async ctx => {
  const articleID = ctx.query.id;
  const [errArticle, articleData]: any = await to(
    sql(`SELECT id,title,category,release_date,visits,markdown,audio_src FROM article WHERE id = ${articleID}`),
  );

  if (errArticle) {
    // 处理错误
    return;
  } else {
    const res = articleData.results[0];
    res.markdown = res.markdown.replace(/@@/g, '');
    ctx.body = {
      data: articleData.results[0],
    };
  }
});

router.get('/asstic/bg.jpg', async (ctx, next) => {
  let imgSrc = '';
  const dir = '/home/data/wallpaper/';
  const files = await fs.promises.readdir(dir);
  const len = files.length;
  const pos = Math.floor(Math.random() * len);
  imgSrc = files[pos];
  ctx.set({
    'Content-Type': 'application/image',
  });
  ctx.body = await fs.promises.readFile(`${dir}${imgSrc}`);
  await next();
});

export {router as userRouter};
